﻿using System;
using RestSharp;
using Spotted.Data.Models;

namespace Spotted.Data.Repositories.Impl
{
    public class RestJsonSpotRepository : ISpotRepository
    {
        private const string BaseUrl = "http://192.168.1.101/SpottedWebApi/api";

        #region Implementation of ISpotRepository

        /// <summary>
        /// Add a new spot 
        /// </summary>
        /// <param name="viewModel">The data to transmit to the web service to add a new spot</param>
        public void AddNewSpot(AddNewSpotViewModel viewModel)
        {
            RestClient client = new RestClient(BaseUrl);
            RestRequest request = new RestRequest("Spot", Method.PUT);
            request.RequestFormat = DataFormat.Json;

            request.AddParameter("name", viewModel.Name);
            request.AddParameter("description", viewModel.Description);
            request.AddParameter("intention", viewModel.IntentionId);
            request.AddParameter("latitude", viewModel.Latitude);
            request.AddParameter("longitude", viewModel.Longitude);

            client.ExecuteAsync(request, (response, handler) =>
                                             {
                                                 //var jsonObject = JObject.Parse(response.Content);
                                                 PutPicture(1, viewModel.ImageData);
                                             });
        }

        public event EventHandler AddNewSpotCompleted;

        #endregion

        /// <summary>
        /// Given a Spot Id, create a picture associated with it
        /// </summary>
        /// <param name="id">The SpotID from the Database</param>
        /// <param name="pictureData">The byte data representing the byte data</param>
        private void PutPicture(int id, byte[] pictureData)
        {
            RestClient client = new RestClient(BaseUrl);
            RestRequest request = new RestRequest("Spot/" + id.ToString() + "/Picture", Method.PUT);
            request.RequestFormat = DataFormat.Json;
            
            request.AddFile("fileData", pictureData, "CameraImage.png");

            client.ExecuteAsync(request, (response, handler) =>
                                             {
                                                 return;
                                             });
        }
    }
}
